/**
 * @param {number[]} nums1
 * @param {number[]} nums2
 * @return {number}
 */
export const findMedianSortedArrays = function (nums1, nums2) {
  const len1 = nums1.length
  const len2 = nums2.length
  if (len1 > len2) return findMedianSortedArrays(nums2, nums1)
  //   if (len1 === 0) {
  //       return len2 % 2 === 0 ?
  //             (nums2[len2 / 2 - 1] + nums2[len2 / 2]) / 2 :
  //             nums2[Math.floor(len2 / 2)]
  //   }
  const leftTotal = (len1 + len2 + 1) >> 1
  //   console.log('leftTotal', leftTotal)
  let start = 0
  let end = len1
  while (start <= end) {
    const i = (end + start + 1) >> 1
    const j = leftTotal - i
    const l1 = i - 1 < 0 ? -Infinity : nums1[i - 1]
    const l2 = j - 1 < 0 ? -Infinity : nums2[j - 1]
    const r1 = i >= len1 ? Infinity : nums1[i]
    const r2 = j >= len2 ? Infinity : nums2[j]
    //   console.log(l1, l2, r1, r2)
    if (l1 > r2) {
      end = i - 1
    } else if (l2 > r1) {
      start = i
    } else {
      return (len1 + len2) % 2 === 0 ? (Math.max(l1, l2) + Math.min(r1, r2)) / 2 : Math.max(l1, l2)
    }
  }
}
